package com.alan.sso.share.utils;

import com.alan.sso.share.bean.Constant;
import com.alan.sso.share.bean.SsoConfigData;
import com.alan.sso.share.bean.SsoUser;
import com.alan.sso.share.filter.SsoAuthenticationFilter;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * @Auther: Alan liu
 * @Date: 2018/12/21 15:56
 * @Description: SsoSession
 */
public class SsoSession {

    public SsoSession() {
    }

    public static SsoUser getCurrentUser(HttpServletRequest request) {
        SsoUser ssoUser = SsoCookieUtils.parseStaffFromSessionCookie(request);
        Long uid = null;
        if (ssoUser != null) {
            SsoSessionStorage.getInstance().putIfAbsent(ssoUser);
            uid = ssoUser.getId();
        } else {
            String ssoUserResult = (String)request.getAttribute(Constant.K_SESSION_ATTR_KEY);
            if (StringUtils.isNotBlank(ssoUserResult)) {
                SsoUser tempSso = (SsoUser) JSONObject.parseObject(SsoConfigData.newInstance().getAes().decryptFromBase64(ssoUserResult), SsoUser.class);
                if (tempSso != null) {
                    SsoSessionStorage.getInstance().putIfAbsent(tempSso);
                    uid = tempSso.getId();
                }
            }
        }

        return SsoSessionStorage.getInstance().getSsoUser(uid);
    }

    public static String logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String cookieValue = SsoCookieUtils.getCookieValue(request, Constant.K_SESSION_KEY);
        Cookie cookie = new Cookie(Constant.K_SESSION_KEY, cookieValue);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return (new URIBuilder(SsoConfigData.newInstance().getLogoutUrl())).toString();
    }

    public static String logout(HttpServletRequest request, HttpServletResponse response, String callbackURL) throws Exception {
        String cookieValue = SsoCookieUtils.getCookieValue(request, Constant.K_SESSION_KEY);
        Cookie cookie = new Cookie(Constant.K_SESSION_KEY, cookieValue);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return (new URIBuilder(SsoConfigData.newInstance().getLogoutUrl())).addParameter(Constant.K_TARGET, URLEncoder.encode(callbackURL, SsoAuthenticationFilter.encoding)).toString();
    }

}
